package club.zhilin.guli.service.edu.service.impl;

import club.zhilin.guli.service.edu.domain.Chapter;
import club.zhilin.guli.service.edu.domain.Video;
import club.zhilin.guli.service.edu.domain.vo.ChapterVO;
import club.zhilin.guli.service.edu.domain.vo.VideoVO;
import club.zhilin.guli.service.edu.mapper.ChapterMapper;
import club.zhilin.guli.service.edu.mapper.VideoMapper;
import club.zhilin.guli.service.edu.service.IChapterService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zhilin
 * @since 2022-01-11 15:29:01
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements IChapterService {

    private final VideoMapper videoMapper;

    @Override
    public boolean removeChapterById(String id) {
        videoMapper.delete(new LambdaQueryWrapper<Video>().eq(Video::getChapterId, id));
        // 删除
        return this.removeById(id);
    }

    @Override
    public List<ChapterVO> nestedList(String courseId) {
        // 获取章节信息
        List<Chapter> chapters = baseMapper.selectList(new LambdaQueryWrapper<Chapter>().eq(Chapter::getCourseId, courseId).orderByAsc(Arrays.asList(Chapter::getSort, Chapter::getId)));
        List<Video> videos = videoMapper.selectList(new LambdaQueryWrapper<Video>().eq(Video::getCourseId, courseId).orderByAsc(Arrays.asList(Video::getSort, Video::getId)));
        // 通过courseId获取所有Video
        return chapters.stream().map(item -> {
            ChapterVO vo = new ChapterVO();
            BeanUtils.copyProperties(item, vo);
            List<VideoVO> children = new ArrayList<>();
            videos.forEach(val -> {
                if (item.getId().equals(val.getChapterId())) {
                    VideoVO videoVO = new VideoVO();
                    BeanUtils.copyProperties(val, videoVO);
                    children.add(videoVO);
                }
            });
            vo.setChildren(children);
            return vo;
        }).collect(Collectors.toList());
    }
}
